package com.pan.concurrency.thread;

/**
 * <p>
 *  代码同步块：使关键性执行代码由并行编程串行
 *
 *  1. run 代码段中有多行，相关的关键性代码 也不是tickets-- 所以不是原子性的。
 *  这段代码在多线程出现问题了。卖出了相同的两张票。
 *
 *  2. 在Synchronized3Thread中改造
 *
 *  3. synchronized全部包裹整段代码 性能太低了。优化与synchronized在synchronized4Thread
 * </p>
 *
 * @author kaiji
 * @since 2020/1/25 11:32
 */
public class Synchronized4Thread {

    public static void main(String[] args) {
        Sale4 saleZh = new Sale4("张三");
        Sale4 saleLi = new Sale4("李四");
        // for (int i = 0; i < 10; i++) {
            Thread zhSan = new Thread(saleZh);
            Thread liSi = new Thread(saleLi);

            zhSan.start();
            liSi.start();
        // }


    }



}

class Sale4 implements Runnable {
    private String username;
    private static int tickets = 100;
    private static final Object lock = new Object();

    Sale4(String username) {
        this.username = username;
    }

    /**
     * 使用 double check
     */
    @Override
    public void run() {
        while (tickets > 0) {
            try {
                Thread.sleep(100);
            } catch (Exception ignored) {
            }
            synchronized (lock) {
                if (tickets > 0) {
                    int tmp = tickets;
                    tickets = tmp - 1;
                    System.out.println(username + "卖票成功，当前票号为：" + tmp);
                }
            }
        }
    }
}



